home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 September / macformat-004.iso / Shareware City / Graphics / VideoToolbox ƒ / VideoToolboxSources / VBLInstall.c < prev    next >
Encoding:
Text File  |  1994-07-07  |  14.1 KB  |  331 lines  |  [TEXT/KAHL]

  1. /*
  2. VBLInstall.c
  3.  
  4. This is the Apple-recommended way of synchronizing your program to a video
  5. display. In the Macintosh, interrupt service routines run at a high processor
  6. priority, i.e. they block interrupts while they run, so Apple advises that they
  7. be very quick, to avoid missing interrupts. That is the approach taken here,
  8. using the interrupt service routines solely to bump a frame counter and set a
  9. newFrame flag to true. Typically your main program will iteratively test the
  10. newFrame flag and, when it's true, clear it and do some action that you want to
  11. do once per frame, in synch with the video frames.
  12.  
  13. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,int frames);
  14.  
  15. The first argument is a pointer to a user-supplied data structure. "device" is a
  16. handle to the video screen that you want to synchronize to, or NULL if you want
  17. to synchronize to the System VBL rate (usually 60.15 Hz). The last argument,
  18. "frames", specifies how many times you want the interrupt to occur before the
  19. routine disables itself. If frames<0 then the interrupt will recur indefinitely.
  20.  
  21. VBLInstall sets noiseVBL.framesDesired and noiseVBL.framesLeft equal to
  22. "frames". While noiseVBL.framesLeft!=0, at each end-of-frame interrupt
  23. noiseVBL.newFrame will be set to 1. noiseVBL.framesLeft will be decremented if
  24. it's >0, but left alone if it's negative. If noiseVBL.framesLeft is decremented
  25. to zero then the interrupt service routine is done, and won't reenable the
  26. interrupt.
  27.  
  28. Here's a minimal program, extracted from NoiseVBL.c, that uses these routines to
  29. show a 100-frame movie, with a new image on each video frame:
  30.  
  31.     VBLTaskAndA5 noiseVBL;
  32.     GDHandle device=GetMainDevice();
  33.     int frames=100,error;
  34.  
  35.     noiseVBL.subroutine=NULL;                // request default subroutine
  36.     error=VBLInstall(&noiseVBL,device,frames);
  37.     if(error)PrintfExit("VBLInstall error %d\n",error);
  38.     noiseVBL.vbl.vblCount=1;    // enable the interrupt service routine
  39.     while(noiseVBL.framesLeft){
  40.         if(noiseVBL.newFrame){
  41.             noiseVBL.newFrame=0;
  42.             CopyBitsQuickly((BitMap *)&(movie[noiseVBL.framesLeft])
  43.                 ,(BitMap *)*((CGrafPtr)window)->portPixMap
  44.                 ,&noiseImage[0].bounds,&window->portRect,srcCopy,NULL);
  45.         }
  46.     }
  47.     VBLRemove(&noiseVBL);
  48.  
  49. Apple warns that interrupt service routines and any data that they access must
  50. be locked into memory, not swapped out, e.g. due to operation of the Memory
  51. Manager or Virtual Memory. It is dangerous to allow your compiler to install
  52. debugging code into interrupt service routines. It is VERY important that you
  53. call VBLRemove() before quitting. Once installed, slot-based interrupt tasks
  54. keep going forever. (Turning off vblData->vbl.vblCount disables the routine, but
  55. doesn't remove it.) The tasks are not removed by the Finder or System when your
  56. application finishes, even though the interrupt service routine's code and data
  57. will probably be overwritten.
  58.  
  59. Actually, things aren't that bad, because I've added a call to _atexit()
  60. requesting that all the VBL tasks installed by VBLInstall() be removed whenever
  61. the program terminates, whether normally or abnormally. This prevents the
  62. otherwise very annoying crash that would accompany premature termination, e.g.
  63. by typing command-., while the VBL task is active.
  64.  
  65. Writing an interrupt service routine, to be called once per video frame, is
  66. slightly tricky. VBLInterruptServiceRoutine does all the dirty work, and then
  67. calls a user-supplied subroutine that does whatever you want. If all you want to
  68. do is advance a frame counter until you reach the desired number of frames then
  69. you may wish to use the default FrameSubroutine() instead of writing your own.
  70. Put the address of whatever routine you want to use into the "subroutine"
  71. element of the VBLTaskAndA5 structure, or, to request use of FrameSubroutine,
  72. supply the address NULL. However, if your compiler uses Universal Headers, then you 
  73. must supply a Universal Procedure Pointer instead of the subroutine address:
  74.  
  75. #if USESROUTINEDESCRIPTORS
  76.     noiseVBL.subroutine=NewVBLProc(myRoutine);
  77. #else
  78.     noiseVBL.subroutine=myRoutine;
  79. #endif
  80.  
  81. FrameSubroutine() uses Timer.c. If this program runs on an old System (pre
  82. 6.05?) lacking the Revised Time Manager, which Timer.c requires, then
  83. SimpleVBLSubroutine() will be used instead. The Timer is used to discard
  84. spurious interrupts that occur within 5 ms of the previous. This is necessary
  85. because some of the Apple video cards generate several interrupts during the
  86. vertical blanking interval, even though Apple's documentation clearly indicates
  87. that they should only generate one. The fix (holding off for 5 ms) was suggested
  88. by Raynald Comtois.
  89.  
  90. The 1992 Apple "Inside Macintosh: Processes" book explains how to code a task
  91. that is to be performed each time your video device produces a vertical blanking
  92. level (i.e. between video frames). It's quite tricky. Therefore I wrote a
  93. generic one, that in turn, calls your custom one, after all the tricky bits have
  94. been taken care of.
  95.  
  96. There are some subtleties to the VBL interrupt service routine. The main one is
  97. that all the Macintosh compilers reference global variables relative to register
  98. A5, but register A5 may have the wrong value (corresponding to a different
  99. application) at interrupt time. So we save the right value of A5 inside our
  100. structure and restore A5 before calling our Task().
  101.  
  102. A further subtlety is that the new generation of optimizing compilers might
  103. notice that A5 is being modified, so it would be dangerous to access globals at
  104. all in InterruptServiceRoutine(), even though it's safe to do so in Task(). In
  105. fact Task() doesn't use any globals, but it could.
  106.  
  107. The fact that the address of our structure is in register A0 when the interrupt
  108. service routine is called results from the fact that the low level hardware VBL
  109. interrupt is intercepted by the operating system, which then calls our routine.
  110.  
  111. The VBLTaskAndA5 struct extends Apple's VBLTask struct by adding some useful
  112. information at the end. You may choose to copy this, or define your own, adding
  113. more stuff at the end. However, you may not want to bother, considering that
  114. your interrupt service routine can freely access global variables.
  115. Alternatively, I added a generic pointer at the end, which you may use to pass
  116. the address of any stuff that you want to access within your subroutine.
  117.  
  118. Macintosh Technical Note 180 ("Multifinder Miscellanea"), p. 5 says:
  119. "GetVBLRec() returns the address of the VBLRec associated with our VBL task.
  120. This works because on entry into the VBL task, A0 points to the theVBLTask field
  121. in the VBLRec record, which is the first field in the record and that is the
  122. address we return. Note that this method works whether the VBLRec is allocated
  123. globally, in the heap...or...on the stack. ... This trick allows us to get to
  124. the saved A5, but it could also be used to get to anything we wanted to store in
  125. the record." (quoted by Jamie McCarthy in comp.sys.mac.prog 10/15/92.)
  126.  
  127. HISTORY:
  128. 8/22/92 dgp wrote it, based on code extracted from my NoiseVBL.c
  129. 8/26/92    dgp    added VBLRemoveAll(), which is automatically placed in the _atexit()
  130.             queue, so it all your VBL tasks will be removed from the queue when
  131.             your program exits, whether normal or abnormally.
  132. 9/9/92    dgp    fixed erroneous attempt to use slot zero when NULL device was passed.
  133. 9/10/92    dgp    added calls to VM to HoldMemory() and UnHoldMemory(). According to Apple's
  134.             Memory book this isn't strictly necessary, since VBL tasks will 
  135.             be called only when it's safe.
  136. 9/17/92    dgp    Transferred FrameSubroutine() here from GDFrameRate.c. Now use 
  137.             FrameSubroutine() instead of SimpleVBLSubroutine() as the default,
  138.             provided we can use Timer.c, otherwise fall back to using 
  139.             SimpleVBLSubroutine.
  140. 10/9/92    dgp    Automatically set up and dispose of the timer used by FrameSubroutine.
  141.             Added a field to the VBLTaskAndA5 structure to hold the timer pointer,
  142.             instead of using up the generic ptr.
  143.             WARNING: old programs (written during 9/92) that explicitly request use of 
  144.             FrameSubroutine must be changed, because at that time it was the user's 
  145.             responsibility to set up and dispose of the timer, whereas it's now done 
  146.             for you. To remind you to make this change "FrameSubroutine" is no longer 
  147.             in VideoToolbox.h, it's treated as a private routine here. To obtain the 
  148.             services of FrameSubroutine, just specify a NULL in the VBLTaskAndA5 
  149.             subroutine field.
  150. 11/17/92 dgp In VBLRemove(), first disable the interrupt, then clean up.
  151.             Fixed error that could cause bus error in VBLRemoveAll.
  152.             VBLInstall() now installs VBLRemoveAll() only once in the _atexit()
  153.             queue, no matter how many times you call it.
  154. 11/24/92 dgp Minor updating of comments.
  155. 7/9/93    dgp    Test MATLAB in if() instead of #if. 
  156. 2/28/94    dgp    In response to query by Mike Tarr (tarr-michael@CS.YALE.EDU), changed 
  157.             frames argument from int to long, and now allow frames==-1 to request 
  158.             that the interrupt service routine continue working indefinitely.
  159. 3/5/94    dgp    In response to a bug report by Mike Tarr, finished the 2/28/94 change,
  160.             which I'd foolishly only done to SimpleVBLSubroutine and not to 
  161.             FrameSubroutine.
  162. 5/28/94    dgp    Made compatible with Apple's Universal Headers. I also attempted to
  163.             make the code PowerPC compatible, but that remains to be tested.
  164. */
  165. #include "VideoToolbox.h"
  166. #include <Traps.h>
  167. //#include <Retrace.h>
  168. void VBLRemoveAll(void);
  169. #if !defined(NewVBLProc)
  170.     typedef ProcPtr UniversalProcPtr;
  171.     #define NewVBLProc(userRoutine) (UniversalProcPtr)(userRoutine)
  172.     #define DisposeRoutineDescriptor(userRoutine) ()
  173. #endif
  174. #if __powerc
  175.     void VBLInterruptServiceRoutine(register VBLTaskAndA5 *vblData);
  176. #else
  177.     void VBLInterruptServiceRoutine(void);
  178. #endif
  179. static void FrameSubroutine(VBLTaskAndA5 *vblData);
  180.  
  181. /* This is just for reference. The original is in VideoToolbox.h
  182. struct VBLTaskAndA5 {
  183.     volatile VBLTask vbl;
  184.     long ourA5;
  185.     #if USESROUTINEDESCRIPTORS
  186.         UniversalProcPtr subroutine;
  187.     #else
  188.         void (*subroutine)(struct VBLTaskAndA5 *vblData);
  189.     #endif
  190.     GDHandle device;
  191.     long slot;
  192.     volatile long newFrame;                // Boolean
  193.     volatile long framesLeft;            // count down to zero
  194.     long framesDesired;
  195.     Timer *frameTimer;                    // time ms since last VBL interrupt, see Timer.c
  196.     void *ptr;                            // use this for whatever you want
  197. };
  198. typedef struct VBLTaskAndA5 VBLTaskAndA5;
  199. */
  200. #define TASK_SIZE 1000    // Generous guess for size of routine
  201. static long vmPresent=0;
  202. static UniversalProcPtr vblProcPtr,frameSubroutineProcPtr,simpleVBLSubroutineProcPtr;
  203.  
  204. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,long frames)
  205. // trivial, but verbose
  206. {
  207.     static int firstTime=1,slotRoutinesAvailable;
  208.     static long timeManagerVersion=0;
  209.     
  210.     if(firstTime){
  211.         firstTime=0;
  212.         slotRoutinesAvailable=TrapAvailable(_SlotVInstall);
  213.         Gestalt(gestaltVMAttr,&vmPresent);
  214.         vmPresent &= gestaltVMPresent;
  215.         if(!MATLAB)_atexit(VBLRemoveAll);
  216.         Gestalt(gestaltTimeMgrVersion,&timeManagerVersion);
  217.         vblProcPtr=NewVBLProc(VBLInterruptServiceRoutine);
  218.         frameSubroutineProcPtr=NewVBLProc(FrameSubroutine);
  219.         simpleVBLSubroutineProcPtr=NewVBLProc(SimpleVBLSubroutine);
  220.     }
  221.     vblData->device=device;
  222.     if(device!=NULL && slotRoutinesAvailable)vblData->slot=GetDeviceSlot(device);
  223.     else vblData->slot=-1;
  224.     vblData->vbl.vblAddr=(void *)vblProcPtr;
  225.     vblData->vbl.qType=vType;
  226.     vblData->vbl.vblCount=0;    /* Initially disable the interrupt service routine */
  227.     vblData->vbl.vblPhase=0;
  228.     vblData->ourA5=SetCurrentA5();
  229.     if(vblData->subroutine==NULL){
  230.         if(timeManagerVersion>=gestaltRevisedTimeMgr){
  231.             vblData->frameTimer=NewTimer();
  232.             StartTimer(vblData->frameTimer);
  233.             vblData->subroutine=(void *)frameSubroutineProcPtr;
  234.         }
  235.         else vblData->subroutine=(void *)simpleVBLSubroutineProcPtr;
  236.     }
  237.     vblData->newFrame=0;
  238.     vblData->framesLeft=vblData->framesDesired=frames;
  239.     if(vmPresent){
  240.         HoldMemory(vblData,sizeof(*vblData));
  241.         HoldMemory(vblData->vbl.vblAddr,TASK_SIZE);
  242.         HoldMemory(vblData->subroutine,TASK_SIZE);
  243.     }
  244.     if(vblData->slot>=0)return SlotVInstall((QElemPtr)vblData,vblData->slot);
  245.     else return VInstall((QElemPtr)vblData);
  246. }
  247.  
  248. OSErr VBLRemove(VBLTaskAndA5 *vblData)
  249. {
  250.     OSErr error;
  251.  
  252.     // only remove it if we installed it
  253.     if(vblData->vbl.vblAddr != vblProcPtr)return;
  254.     if(vblData->slot>=0)error=SlotVRemove((QElemPtr)vblData,vblData->slot);
  255.     else error=VRemove((QElemPtr)vblData);
  256.     if(vmPresent){
  257.         UnholdMemory(vblData,sizeof(vblData));
  258.         UnholdMemory(vblData->vbl.vblAddr,TASK_SIZE);
  259.         UnholdMemory(vblData->subroutine,TASK_SIZE);
  260.     }
  261.     if(vblData->subroutine==(void *)frameSubroutineProcPtr && vblData->frameTimer!=NULL)
  262.         DisposeTimer(vblData->frameTimer);
  263.     return error;
  264. }
  265.  
  266. void VBLRemoveAll(void)
  267. {
  268.     QHdrPtr qHeader;
  269.     QElemPtr q;
  270.     
  271.     qHeader=GetVBLQHdr();
  272.     q=qHeader->qHead;
  273.     while(q!=NULL){
  274.         VBLRemove((VBLTaskAndA5 *)q);    // only removes ours
  275.         q=q->qLink;
  276.     }
  277. }    
  278.  
  279. #pragma options(!profile)    // it would be dangerous to call the profiler from here
  280. #pragma options(assign_registers,redundant_loads)
  281.  
  282. #if __powerc
  283.     void VBLInterruptServiceRoutine(register VBLTaskAndA5 *vblData)
  284.     {
  285.         CallVBLProc(vblData->subroutine,vblData);    // call user's task, pass data ptr
  286.     }
  287. #else
  288.     Ptr GetA0(void)=0x2008;    /* MOVE.L A0,D0 */
  289.  
  290.     void VBLInterruptServiceRoutine(void)
  291.     {
  292.         register long oldA5;
  293.         register VBLTaskAndA5 *vblData;
  294.     
  295.         vblData = (VBLTaskAndA5 *)GetA0();
  296.         oldA5 = SetA5(vblData->ourA5);
  297.         // call user's task, pass data ptr
  298.         #if USESROUTINEDESCRIPTORS
  299. // WARNING: uppVBLProcInfo is the wrong selector.
  300.             CallUniversalProc(vblData->subroutine,uppVBLProcInfo,vblData);
  301.         #else
  302.             (*vblData->subroutine)(vblData);
  303.         #endif
  304.         SetA5(oldA5);
  305.     }
  306. #endif
  307.  
  308. void SimpleVBLSubroutine(VBLTaskAndA5 *vblData)
  309. {
  310.     vblData->newFrame=1;
  311.     if(vblData->framesLeft>0)vblData->framesLeft--;
  312.     if(vblData->framesLeft!=0)vblData->vbl.vblCount=1;
  313. }
  314.  
  315. static void FrameSubroutine(VBLTaskAndA5 *vblData)
  316. {
  317.     // The 1991-2 Apple video cards emit several vbl interrupts per frame,
  318.     // which violates Apple's documentation.
  319.     // So we use the Time Manager to ignore any interrupt that occurs within 5 ms
  320.     // of the most recent interrupt, for that video device.
  321.     // Thus this frame counter should work correctly on all video cards.
  322.     // Suggested by Raynald Comtois.
  323.     if(StopTimer(vblData->frameTimer)>5000){
  324.         vblData->newFrame=1;                                    // set new-frame flag
  325.         if(vblData->framesLeft>0)vblData->framesLeft--;
  326.         if(vblData->framesLeft!=0)vblData->vbl.vblCount=1;        // re-enable interrupt
  327.     }else vblData->vbl.vblCount=1;                                // re-enable interrupt
  328.     StartTimer(vblData->frameTimer);
  329. }
  330.  
  331.